import os
from tkinter import messagebox


class ClothingColorExtractor:

    def process_dataset(self):
        dataset_path = self.dataset_path_var.get()
        if not os.path.exists(dataset_path):
            messagebox.showerror("错误", f"路径不存在: {dataset_path}")
            return

        image_files = []
        for file in os.listdir(dataset_path):
            if file.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
                image_files.append(os.path.join(dataset_path, file))

        if not image_files:
            messagebox.showinfo("提示", f"路径下没有找到图片文件: {dataset_path}")
            return

        total = len(image_files)
        self.test_report = []
        for i, img_path in tqdm(enumerate(image_files), total=total, desc="处理图片"):
            try:
                result = self.analyze_image(img_path)
                self.processed_images[img_path] = result
                self.test_report.append({
                    "image_path": img_path,
                    "dominant_colors": result["colors"],
                    "percentages": result["percentages"]
                })
                print(f"已处理 {i + 1}/{total}: {img_path}")
            except Exception as e:
                print(f"处理失败 {img_path}: {str(e)}")

        self.generate_test_report()
        messagebox.showinfo("完成", f"已完成处理 {len(self.processed_images)} 张图片，测试报告已生成")

    def generate_test_report(self):
        report_path = "test_report.txt"
        with open(report_path, "w", encoding="utf-8") as f:
            f.write("数据集批量测试报告\n")
            f.write("=" * 50 + "\n")
            for item in self.test_report:
                f.write(f"图片路径: {item['image_path']}\n")
                f.write("主色及百分比:\n")
                for color, percentage in zip(item["dominant_colors"], item["percentages"]):
                    f.write(f"  颜色: {color}, 百分比: {percentage * 100:.2f}%\n")
                f.write("-" * 50 + "\n")